/**
 * 配置
 * */
package org.zmhhxl.api.auth.domain.entity.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.zmhhxl.api.auth.domain.entity.Role;
import org.zmhhxl.api.auth.domain.entity.UserInfo;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * 用户信息反序列化，自定义
 * */
public class CustomUserInfoDeserializer extends JsonDeserializer<UserInfo> {
   @Override
   public UserInfo deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
      ObjectMapper mapper = (ObjectMapper) p.getCodec();
      JsonNode node = mapper.readTree(p);

      UserInfo userInfo = new UserInfo();
      userInfo.setId(node.get("id").asLong());
      userInfo.setUsername(node.get("username").asText());
      userInfo.setPassword(node.get("password").asText());
      userInfo.setNickName(node.get("nickName").asText());
      userInfo.setEmail(node.get("email").asText());
      userInfo.setPhone(node.get("phone").asText());
      userInfo.setRealName(node.get("realName").asText());
      userInfo.setAddress(node.get("address").asText());
      userInfo.setAvatarUrl(node.get("avatarUrl").asText());
      userInfo.setBirthday(node.get("birthday").asText());

      userInfo.setEnabled(node.get("enabled").asBoolean());

//      if (node.has("thirdPartyUser")) {
//         val thirdPartyUserNode = node.get("thirdPartyUser");
//      }

      if (node.has("authorities")) {
         ArrayNode rolesNode = (ArrayNode) node.get("authorities");
         Set<Role> roles = new HashSet<>();
         for (JsonNode roleNode : rolesNode) {
            Role roleNode1 = mapper.readValue(roleNode.toString(), Role.class);
            roles.add(roleNode1);
         }
         userInfo.setAuthorities(roles);
      }

      return userInfo;
   }
}
